package dao.impl;

import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import common.CommonUtil;
import vo.Customer;
import dao.CustomerDao;

@Repository    //@Repository以为持久层
public class CustomerDaoImpl implements CustomerDao {
    @Resource
	private SessionFactory sessionFactory;

//	public void setSessionFactory(SessionFactory sessionFactory) {
//		this.sessionFactory = sessionFactory;
//	}

	//@Override
	public void addCustomer(Customer customer) {
		System.out.println("开始添加");
		for (int i=0; i<50; i++) {
			Customer newCustomer = new Customer();
			newCustomer.setName(customer.getName() + i);
			newCustomer.setAddr(customer.getAddr() + i);
			//newCustomer.setBirthday(customer.getBirthday());
			newCustomer.setBirthday(CommonUtil.getDateStr());
			newCustomer.setHukou(customer.getHukou());
			newCustomer.setEmail(customer.getEmail() + i);
			newCustomer.setUrl(customer.getUrl() + i);
			newCustomer.setHeight(customer.getHeight());
			
			sessionFactory.getCurrentSession().saveOrUpdate(newCustomer);
		}
	}

	//@Override
	public List<Object> searchByName(String name, int start, int length) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Customer where name like '%" + name + "%'");
		query.setFirstResult(start);
		query.setMaxResults(length);
		
		return (List<Object>)query.list();
	}
	
	//@Override
	public Long count(String name) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("select count(*) from Customer where name like '%" + name + "%'");
		Long count = (Long)query.list().get(0);
		
		return count;
	}
}
